package it.progettoso.thread;

import it.progettoso.activity.LockScreenActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.PowerManager;
import android.telephony.TelephonyManager;


public class CallThread implements Runnable {
	private Context c;
	private boolean locked=false;
	

	public CallThread(Context context, boolean locked) {
		c=context;
		this.locked=locked;
	}

	@Override
	public void run() {
		
		TelephonyManager telephonyManager=(TelephonyManager) c.getSystemService(Context.TELEPHONY_SERVICE);
		while (telephonyManager.getCallState()< 2 ){
		}
		
		if(locked)
	       reLock();
		else
			invisibleCallOut();

	}
	
	public void reLock(){
		LockScreenActivity.getInstance("lock").finish();
		PowerManager pm = (PowerManager)c.getSystemService(Context.POWER_SERVICE);
		PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK
				| PowerManager.ACQUIRE_CAUSES_WAKEUP,
		"My Lock");
		wl.acquire();
		Intent lockintent = new Intent(c, LockScreenActivity.class);
		lockintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		c.startActivity(lockintent);
		wl.release();

		HandlerThread lockthread = new HandlerThread("Lock Thread");
		Runnable t_lock = new ControlLockThread(c,1);
		lockthread.start();
		new Handler(lockthread.getLooper()).post(t_lock);
		
	}
	
	public void invisibleCallOut(){
		Intent showOptions = new Intent(Intent.ACTION_MAIN);
		showOptions.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	    showOptions.addCategory(Intent.CATEGORY_HOME);
	    c.startActivity(showOptions);
	}

}
